/*
 * @Title: 购物车
 * @Author: JSL、zhuhaojie
 * @Date:   2018-10-16
 * @Last Modified by:   JSL
 * @Last Modified time: 2018-11-29
 */

var dataInfo = new Object(),
  template = {
    init: function() {
      Vue.use(VueLazyload, {
        preLoad: 1.3,
        error: 'https://h5.meetao.com/img/product/init.png',
        loading: 'https://h5.meetao.com/img/product/init.png',
        attempt: 1
      });
      dataInfo.init = new Vue({
        el: '#app',
        data: {
          versions: versions,
          icon: {
            normal: '../img/index/shouhui.png',
            active: '../img/index/shouhong.png',
            normal1: '../img/index/gouhui.png',
            active1: '../img/index/gouhong.png',
            active2: '../img/index/myhong.png',
            normal2: '../img/index/myhui.png',
            active3: '../img/index/pthong.png',
            normal3: '../img/index/pthui.png',
            active4: "../img/index/votegoods.png",
            normal4: "../img/index/votegoodsgray.png",
          },
          active: 2,
          hot: [], //热卖商品、推荐商品集合
          isFx: 1, //是否分销
          isDz: 0, //是否店主
          cartOutNum: 2, //过期购物车判断
          cartGoods: { //实际购物车数据
            result: [],
            cartOutResult: [],
            price: '',
          },
          cartGoodsResult: [], //原有购物车数据
          cartSubmitInfo: [], //提交购物车info
          checked: false, //全选
          deleteGoodsCode: '', //删除商品编码
          images: [
            'https://img.yzcdn.cn/public_files/2017/09/05/fd08f07665ed67d50e11b32a21ce0682.jpg',
            'https://img.yzcdn.cn/public_files/2017/09/05/fd08f07665ed67d50e11b32a21ce0682.jpg'
          ],
        },
        methods: {
          getCartGoods: function() { //查询购物车
            ajaxTemplate(addressUrl + SERVICE.queryCartGoods, function(data) {
              console.log(data);
              if (data.tag == 0) {
                data.data.checkNum == 0 ? $('.van-submit-bar .van-button__text').html('结算') : $('.van-submit-bar .van-button__text').html('结算(' + data.data.checkNum + ')');
                dataInfo.init.cartGoods = data.data;
                dataInfo.init.cartGoodsResult = JSON.parse(JSON.stringify(data.data.result));
              } else {
                dataInfo.init.$toast(data.errMsg);
              };
            }, {
              userId: userId
            });
          },
          recommendGoods: function() { // 推荐商品
            ajaxTemplate(addressUrl + SERVICE.queryGoodsRecommend, function(data) {
              if (data.tag == 0) {
                var daTa = data.data.result;
                daTa.forEach(function(item, index) {
                  if (item.isKill !== 0) {
                    dataInfo.init.hot.push(item);
                  };
                });
              } else {
                dataInfo.init.$toast(data.errMsg);
              };
            }, {});
          },
          toProduct: function(data) {
            jumpProductDetails(data);
          },
          submitData: function() {
            if (this.cartGoods.result.length > 0) {
              this.cartSubmitInfo = [];
              this.cartGoods.result.forEach(function(item, index) {
                if (item.check == 1) {
                  var objectLength = dataInfo.init.cartSubmitInfo.length;
                  dataInfo.init.cartSubmitInfo[objectLength] = {};
                  dataInfo.init.cartSubmitInfo[objectLength].goodsCode = item.goodsCode;
                  dataInfo.init.cartSubmitInfo[objectLength].num = item.num;
                  dataInfo.init.cartSubmitInfo[objectLength].isKill = item.isKill;
                  dataInfo.init.cartSubmitInfo[objectLength].killCode = item.killCode;
                };
              });
              if (this.cartSubmitInfo.length > 0) {
                this.$toast.loading({
                  forbidClick: true,
                  message: '订单生成中...',
                  loadingType: 'spinner',
                  duration: 0,
                });
                this.orderforh5();
              } else {
                dataInfo.init.$toast('请选择要购买的商品');
              };
            } else {
              dataInfo.init.$toast('购物车空空如也');
            };
          },
          updateCartGoodsNum: function(goodsCode, num, numData) { //修改购物车商品数量
            ajaxTemplate(addressUrl + SERVICE.updateCartGoodsNum, function(data) {
              console.log(data);
              if (data.tag == 0) {
                dataInfo.init.cartGoods.price = data.data.result.price;
                data.data.result.checkNum == 0 ? $('.van-submit-bar .van-button__text').html('结算') : $('.van-submit-bar .van-button__text').html('结算(' + data.data.result.checkNum + ')');
                !!numData ? dataInfo.init.cartGoodsResult = JSON.parse(JSON.stringify(dataInfo.init.cartGoods.result)) : "";
              } else {
                dataInfo.init.$toast(data.errMsg);
                !!numData ? dataInfo.init.cartGoods.result = JSON.parse(JSON.stringify(dataInfo.init.cartGoodsResult)) : "";
              };
            }, {
              userId: userId,
              goodsCode: goodsCode,
              num: num
            });
          },
          updateCartGoodsCheck: function(goodsCode, check) { //修改购物车选中商品
            ajaxTemplate(addressUrl + SERVICE.updateCartGoodsCheck, function(data) {
              console.log(data);
              if (data.tag == 0) {
                dataInfo.init.cartGoods.price = data.data.result.price;
                data.data.result.checkNum == 0 ? $('.van-submit-bar .van-button__text').html('结算') : $('.van-submit-bar .van-button__text').html('结算(' + data.data.result.checkNum + ')');
              } else {
                dataInfo.init.$toast(data.errMsg);
              };
            }, {
              userId: userId,
              goodsCode: goodsCode,
              check: check
            });
          },
          orderforh5: function() { //最终提交
            ajaxTemplate(addressUrl + SERVICE.orderforh5, function(data) {
              console.log(data);
              if (data.tag == 0) {
                dataInfo.zmtMallOrder = data.data.result;
                dataInfo.init.saveOrderInfo();
              } else {
                dataInfo.init.$toast.clear();
                dataInfo.init.$toast(data.errMsg);
              };
            }, {
              userId: userId,
              goodsInfo: JSON.stringify(this.cartSubmitInfo),
              isGiftPacksOrder: 1
            });
          },
          saveOrderInfo: function() { //提交购物车信息
            ajaxTemplate(addressUrl + SERVICE.cacheCartGoods, function(data) {
              if (data.tag == 0) {
                setCookie('zmtMallOrder', escape(JSON.stringify(data.data.result.id)), 30);
                location.href = "../html/orderFilling.html?buyWay=2";
              } else {
                dataInfo.init.$toast.clear();
                dataInfo.init.$toast(data.errMsg);
              };
            }, {
              // text: JSON.stringify(dataInfo.zmtMallOrder)
              text: JSON.stringify(this.cartSubmitInfo)
            });
          },
          onClose: function(clickPosition, instance) {
            if (clickPosition != 'right') {
              instance.close();
            };
          },
          deleteNum: function(e) {
            this.deleteGoodsCode = e.goodsCode;
            this.deleteCartGoods(2);
          },
          clearOutGoods: function() { //清空失效商品-all
            this.deleteGoodsCode = '';
            this.cartGoods.cartOutResult.forEach(function(item, index) {
              dataInfo.init.deleteGoodsCode += item.goodsCode + ',';
            });
            this.deleteGoodsCode.substring(0, this.deleteGoodsCode.length - 1);
            this.$toast.loading({
              forbidClick: true,
              message: '数据请求中...',
              loadingType: 'spinner',
              duration: 0,
            });
            this.deleteCartGoods(1);
          },
          deleteCartGoods: function(num) { //清空失效商品-single
            ajaxTemplate(addressUrl + SERVICE.deleteCartGoods, function(data) {
              console.log(data);
              dataInfo.init.$toast.clear();
              if (data.tag == 0) { //价格更新、新旧数据更新
                dataInfo.init.cartGoods.price = data.data.result.price;
                data.data.result.checkNum == 0 ? $('.van-submit-bar .van-button__text').html('结算') : $('.van-submit-bar .van-button__text').html('结算(' + data.data.result.checkNum + ')');
                if (num == 1) { //清理全部
                  dataInfo.init.cartOutNum = 1;
                  dataInfo.init.cartGoods.cartOutResult = [];
                } else { //单品清理
                  dataInfo.init.cartGoodsResult.forEach(function(item, index) {
                    if (item.goodsCode == dataInfo.init.deleteGoodsCode) {
                      dataInfo.init.cartGoodsResult.splice(index, 1);
                    };
                  });
                  dataInfo.init.cartGoods.result.forEach(function(item, index) {
                    if (item.goodsCode == dataInfo.init.deleteGoodsCode) {
                      dataInfo.init.cartGoods.result.splice(index, 1);
                    };
                  });
                };
                dataInfo.init.$toast.success({
                  duration: 1000,
                  message: '删除成功',
                  forbidClick: true
                });
              } else {
                dataInfo.init.$toast(data.errMsg);
              };
            }, {
              userId: userId,
              goodsCode: this.deleteGoodsCode
            });
          },
        },
        computed: {
          checkNum: function() {
            dataInfo.checkNum = 0;
            if (this.cartGoods.result.length > 0) {
              this.cartGoods.result.forEach(function(item, index) {
                !!item.check ? dataInfo.checkNum += 1 : '';
              });
            };
            return dataInfo.checkNum;
          },
        },
        watch: {
          'cartGoods.result': {
            handler: function(data) {
              if (data.length > 0) { //购物车有数据
                dataInfo.allCheck = 0;
                data.forEach(function(item, index) {
                  !!item.check ? dataInfo.allCheck += 1 : '';
                  if (item.num < dataInfo.init.cartGoodsResult[index].num) { // -
                    dataInfo.init.updateCartGoodsNum(item.goodsCode, item.num);
                    dataInfo.init.cartGoodsResult = JSON.parse(JSON.stringify(data));
                    return false;
                  } else if (item.num > dataInfo.init.cartGoodsResult[index].num) { // +
                    dataInfo.init.updateCartGoodsNum(item.goodsCode, item.num, 1);
                    return false;
                  } else if (item.check != dataInfo.init.cartGoodsResult[index].check) {
                    dataInfo.init.updateCartGoodsCheck(item.goodsCode, !!item.check ? 1 : 0);
                    !item.check ? dataInfo.unCheck = 1 : '';
                    dataInfo.init.cartGoodsResult = JSON.parse(JSON.stringify(data));
                    return false;
                  };
                });
                //默认是否全选
                dataInfo.allCheck == data.length ? dataInfo.unCheck = 0 : dataInfo.unCheck = 1;
                dataInfo.allCheck == data.length ? dataInfo.init.checked = true : dataInfo.init.checked = false;
              } else { //购物车无数据
                dataInfo.unCheck = 1;
                dataInfo.init.checked = false;
              };

            },
            deep: true,
          },
          checked: function(data) { //全选按钮
            if (!!data) { //全选
              dataInfo.init.cartGoods.result.forEach(function(itm, indx) {
                itm.check = 1;
              });
              dataInfo.allCheck == dataInfo.init.cartGoods.result.length ? '' : dataInfo.init.updateCartGoodsCheck('', 3);
            } else if (!!dataInfo.unCheck) { //全不选
              dataInfo.unCheck = 0;
            } else if (!dataInfo.unCheck) {
              dataInfo.init.cartGoods.result.forEach(function(itm, indx) {
                itm.check = 0;
              });
              dataInfo.init.updateCartGoodsCheck('', 4);
            };
            dataInfo.init.cartGoodsResult = JSON.parse(JSON.stringify(dataInfo.init.cartGoods.result));
          },

        },
      });
      dataInfo.unCheck = 0;
      dataInfo.init.getCartGoods();
      dataInfo.init.recommendGoods();
    },
  }
template.init();
